const config = require('./config')

/** 显示消息提示 */
function showToast(title) {
  wx.showToast({
    title: title,
    icon: 'none',
    duration: 1500,
    mask: true
  })
}

/** 生成请求url */
function buildUrl(path) {
  if (path.indexOf('://') === -1) {
    return config.baseUrl + path
  }
  return path
}

/** 获取请求头 */
function getHeader() {
  return {
    'appId': config.appId,
    'token': 'eyJhbGciOiJIUzI1NiJ9.eyJuYmYiOjE2MTIyMjU2MjgsImlkIjoiQS9zWFB0VGF4bzlmTS9HT0VDK3R5WnExWitwVFlBOTlXRFR5MmprQ3paWT0iLCJleHAiOjE2MTQ4MTc2MjgsImlhdCI6MTYxMjIyNTYyOH0.4KhLVnpcHt2WK8bVjUpIN9Cxzx9nmO7bN4emKYPoYJk',
  }
}

/**
 * 网络请求封装
 * @param url {string} 接口url
 * @param data {Object} 请求数据对象
 * @param method {"GET"|"POST"} 请求方法
 * @param loadMask {string}加载提示文本,设置false则不显示
 * @return {Promise<Object>}
 */
function request(url, data, method, loadMask) {
  let showLoadinged = false, timeoutId = 0;
  //延迟显示Loading
  if (loadMask) {
    timeoutId = setTimeout(() => {
      showLoadinged = true
      wx.showLoading({
        title: loadMask,
        mask: true
      })
    }, 1000)
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url: buildUrl(url),
      data: data,
      header: {...config.header, ...getHeader()},
      method: method,
      success: (res) => {
        if (res.data.success === true) {
          resolve(res.data)
        } else {
          if (config.debug) {
            console.log(res.data)
          }
          reject(res.data)
        }
      },
      fail: (error) => {
        if (config.debug) {
          showToast('网络连接失败')
          console.log('fail:', error)
        }
      },
      complete: (res) => {
        if (loadMask) {
          if (timeoutId) clearTimeout(timeoutId)
          if (showLoadinged === true) wx.hideLoading()
        }
      }
    })
  })
}

module.exports = {
  /**
   * Get网络请求封装
   * @param url {string} 接口url
   * @param data {Object} [data={}] 请求数据对象
   * @param loadMask {string} [loadMask=加载中...] 加载提示文本,默认显示"加载中...",设置false则不显示
   * @return {Promise<Object>}
   */
  get: (url, data = {}, loadMask = '加载中...') => {
    return request(url, data, "GET", loadMask);
  },

  /**
   * Post网络请求封装
   * @param url {string} 接口url
   * @param data {Object} [data={}] 请求数据对象
   * @param loadMask {string} [loadMask=加载中...] 加载提示文本,默认显示"加载中...",设置false则不显示
   * @return {Promise<Object>}
   */
  post: (url, data = {}, loadMask = '加载中...') => {
    return request(url, data, "POST", loadMask);
  },

  /** 显示消息提示 */
  showToast
}